<?php

namespace app\admin\controller\box;

use app\common\controller\Backend;

/**
 * 用户盒子
 *
 * @icon fa fa-circle-o
 */
class Userbox extends Backend {

    /**
     * Box模型对象
     * @var \app\admin\model\user\Box
     */
    protected $model = null;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\user\Box;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $otherwhere[] = ['status', '<', 20];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null, null, $otherwhere);
            $admin_info = db('admin')->where('id', $this->auth->id)->find();
            $admin_where = [];

            if ($admin_info['identity'] == 1) {
                if ($admin_info['province'] != 0) {
                    $admin_where['fa_user_box.province'] = $admin_info['province'];
                }
                if ($admin_info['city'] != 0) {
                    $admin_where['fa_user_box.city'] = $admin_info['city'];
                }
                if ($admin_info['area'] != 0) {
                    $admin_where['fa_user_box.area'] = $admin_info['area'];
                }
                if ($admin_info['quarters_id'] != 0) {
                    $admin_where['fa_user_box.quarters_id'] = $admin_info['quarters_id'];
                }
                if ($admin_info['unit_id'] != 0) {
                    $admin_where['fa_user_box.unit_id'] = $admin_info['unit_id'];
                }
                if ($admin_info['room_id'] != 0) {
                    $admin_where['fa_user_box.room_id'] = $admin_info['room_id'];
                }
            } else if ($admin_info['identity'] == 2) {
                $admin_where['fa_user_box.box_no'] = ['in', $admin_info['box_nos']];
            }
            $total = $this->model
                    ->where($where)
                    ->where($admin_where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->where($admin_where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            if ($list) {
                //获取配置
//                $config_key = 'xiangguanpeizhi';
//                $configInfo = \think\Db::name('configure')->where(['key' => $config_key])->find();
//                $configValue = json_decode($configInfo['desc'],TRUE);
//                $val['referee_price'] = $val['finish_task_num'] * floatval($configValue['rakeback_rate']);
                foreach ($list as &$val) {
                    $val['room_name'] = db('house')->where(['house_id' => $val['room_id']])->value('house_name');
                    $val['unit_name'] = db('house')->where(['house_id' => $val['unit_id']])->value('house_name');
                    $val['quarters_name'] = db('house')->where(['house_id' => $val['quarters_id']])->value('house_name');
                }
                unset($val);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function allot() {
        $id = $this->request->param('ids');
        if ($this->request->isPost()) {
            $infos = input('infos/a');
            if ($infos) {
                $is_repeat = [];
                foreach ($infos as $val) {
                    $is_repeat[] = $val['box_id'];
                }

                if (count($is_repeat) != count(array_unique($is_repeat))) {
                    $this->error('选择的盒子里有相同的编号');
                }

                foreach ($infos as $key => $val) {


                    $user_box_info = db('user_box')->where('box_id', $val['box_id'])->where('status', 30)->find();
                    //预占过的盒子分配
                    if ($user_box_info) {

                        $goods_list = db('user_box_goods')->where('user_box_id', $user_box_info['user_box_id'])->select();

                        $data['box_id'] = $val['box_id'];
                        $data['box_no'] = $user_box_info['box_no'];
                        $data['audit_time'] = date('Y-m-d H:i:s', time());
                        $data['place_time_start'] = date('Y-m-d H:i:s', time());
                        $data['status'] = 1;


                        $box_goods_ids = [];
                        //预占时的商品迁移过来
                        foreach ($goods_list as $goods) {
                            $is_exis = db('user_box_goods')->where(['user_box_id' => $key, 'goods_id' => $goods['goods_id']])->find();

                            $box_goods_ids[] = $goods['box_goods_id'];
                            if ($is_exis) {
                                db('user_box_goods')->where(['user_box_id' => $key, 'goods_id' => $goods['goods_id']])->setInc('stock_num', $goods['stock_num']);
                                db('user_box_goods')->where(['user_box_id' => $key, 'goods_id' => $goods['goods_id']])->setInc('total_num', $goods['stock_num']);
                            } else {
                                unset($goods['box_goods_id']);
                                $goods['user_box_id'] = $key;
                                db('user_box_goods')->insert($goods);
                            }
                        }

                        db('user_box_goods')->where('box_goods_id', 'in', $box_goods_ids)->delete();
                        db('user_box')->where(['user_box_id' => $user_box_info['user_box_id']])->delete();

                        db('user_box')->where(['user_box_id' => $key])->update($data);
                    } else {
                        $data['admin_remark'] = $val['admin_remark'];
                        $data['box_id'] = $val['box_id'];
                        $data['box_no'] = db('box')->where(['box_id' => $val['box_id']])->value('box_no');
                        $data['audit_time'] = date('Y-m-d H:i:s', time());
                        $data['place_time_start'] = date('Y-m-d H:i:s', time());
                        $data['status'] = 1;
                        db('user_box')->where(['user_box_id' => $key])->update($data);
                    }

                    $box['status'] = 1;
                    $box['updatetime'] = date('Y-m-d H:i:s', time());
                    db('box')->where(['box_id' => $val['box_id']])->update($box);

                    //添加库存变动流水
                    $user_box_goods = db('user_box_goods')->where('user_box_id', $key)->select();
                    $stock_log['remark'] = '盒子布放初始库存';
                    $stock_log['change_type'] = 0;
                    $stock_log['change_matters'] = 1;
                    foreach ($user_box_goods as $val) {
                        if ($val['stock_num'] > 0) {
                            $stock_log['box_goods_id'] = $val['box_goods_id'];
                            $stock_log['goods_id'] = $val['goods_id'];
                            $stock_log['change_amount'] = $val['stock_num'];
                            $stock_log['quantity'] = $val['stock_num'];
                            db('stock_log')->insert($stock_log);
                        }
                    }
                }

                $this->success();
//                $this->success('分配成功', url('index'));
            } else {
                $this->error('没有需要保存的数据');
            }
        } else {
            $user_box_list = db('user_box')->where('user_box_id', 'in', $id)->where('status', 0)->select();

            $quarters_ids = [];
            if ($user_box_list) {
                foreach ($user_box_list as &$val) {
                    $val['room_name'] = db('house')->where(['house_id' => $val['room_id']])->value('house_name');
                    $val['unit_name'] = db('house')->where(['house_id' => $val['unit_id']])->value('house_name');
                    $val['quarters_name'] = db('house')->where(['house_id' => $val['quarters_id']])->value('house_name');
                    $quarters_ids[] = $val['quarters_id'];
                }
                unset($val);
            } else {
                $this->redirect(url('index'));
            }


            $box_list = db('box')->field('box_id,box_no')->where('status', 10)->select();

            foreach ($box_list as $key => &$val) {
                $user_box_info = db('user_box')->where('box_id', $val['box_id'])->where('status', 30)->find();

                if ($user_box_info) {

                    if (in_array($user_box_info['quarters_id'], $quarters_ids)) {
                        $goods_list = db('user_box_goods')->where('user_box_id', $user_box_info['user_box_id'])->select();

                        if ($goods_list) {
                            $val['box_no'] .= '--有商品';
                        }
                    } else {
                        unset($box_list[$key]);
                    }
                }
            }

            $this->assign('box_list', $box_list);
            $this->assign('list', $user_box_list);
            $this->assign('ids', $id);
        }
        return $this->view->fetch();
    }

    public function goodslist() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $box_ids = $this->request->param('ids');

            $box_ids = explode(',', $box_ids);

            //获取商品ID
            $goods_ids = db('user_box_goods')->where(['user_box_id' => ['in', $box_ids]])->group('goods_id')->column('goods_id');

            $quarters_id = db('user_box')->where(['user_box_id' => ['in', $box_ids]])->group('quarters_id')->value('quarters_id');

            $otherwhere[] = ['is_deleted', '=', 0];
            $otherwhere[] = ['goods_id', 'in', $goods_ids];

            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null, null, $otherwhere, ['is_deleted' => 'fa_goods.is_deleted']);
            $total = db('goods')
                    ->join('fa_goods_brand', 'fa_goods_brand.brand_id = fa_goods.brand_id', 'left')
                    ->join('fa_goods_cate', 'fa_goods_cate.cate_id = fa_goods.cate_id', 'left')
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = db('goods')
                    ->field('fa_goods.goods_id,fa_goods.goods_logo,fa_goods.goods_title,fa_goods.goods_model,fa_goods.goods_spec,fa_goods.goods_weight,fa_goods.purchase_price,fa_goods.selling_price as goods_price,fa_goods_brand.brand_title,fa_goods_cate.cate_title')
                    ->join('fa_goods_brand', 'fa_goods_brand.brand_id = fa_goods.brand_id', 'left')
                    ->join('fa_goods_cate', 'fa_goods_cate.cate_id = fa_goods.cate_id', 'left')
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            if ($list) {
                foreach ($list as &$val) {
                    $val['selling_price'] = db('house_goods')->where(['house_id' => $quarters_id, 'goods_id' => $val['goods_id']])->value('selling_price');
                    $user_box_goods = db('user_box_goods')->where(['user_box_id' => ['in', $box_ids], 'goods_id' => $val['goods_id']])->find();
                    $val['createtime'] = $user_box_goods['createtime'];
                    $val['stock_num'] = $user_box_goods['stock_num'];
                }
                unset($val);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
//        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function addgoods() {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $box_ids = $this->request->param('ids');


            $quarters_id = db('user_box')->where(['user_box_id' => ['in', $box_ids]])->group('quarters_id')->value('quarters_id');

            //去掉已添加的商品
            $box_goods_ids = db('user_box_goods')->where(['user_box_id' => ['in', $box_ids]])->group('goods_id')->column('goods_id');


            $goods_ids = db('house_goods')->where(['house_id' => $quarters_id, 'goods_id' => ['not in', $box_goods_ids]])->column('goods_id');

            if ($goods_ids) {
                $otherwhere[] = ['goods_id', 'in', $goods_ids];

//            $otherwhere[] = ['house_type', '=', 1];
                $otherwhere[] = ['is_deleted', '=', 0];
                list($where, $sort, $order, $offset, $limit) = $this->buildparams(null, null, $otherwhere);
                $total = db('goods')
                        ->where($where)
                        ->order($sort, $order)
                        ->count();
                $list = db('goods')
                        ->where($where)
                        ->order($sort, $order)
                        ->limit($offset, $limit)
                        ->select();


                $list = collection($list)->toArray();
                if ($list) {
                    foreach ($list as &$val) {
                        $val['brand_title'] = db('goods_brand')->where(['brand_id' => $val['brand_id']])->value('brand_title');
                        $val['cate_title'] = db('goods_cate')->where(['cate_id' => $val['cate_id']])->value('cate_title');
                    }
                    unset($val);
                }

                $result = array("total" => $total, "rows" => $list);

                return json($result);
            } else {
                $result = array("total" => 0, "rows" => []);
                return json($result);
            }
        }

        return $this->view->fetch();
    }

    public function laying() {
        $rid = $this->request->param('rid', 0);
        $laying_list = db('user_box')->where(['room_id' => $rid, 'status' => 20])->select();
        $this->assign('list', $laying_list);
        return $this->view->fetch();
    }

    public function delgoods() {
        $id = input('id', 0, 'intval');
        $box_ids = $this->request->param('ids');

        $data['updatetime'] = date('Y-m-d H:i:s', time());
        $data['is_del'] = 1;
        $data['goods_id'] = $id;

        db('user_box_goods')->where(['goods_id' => $id, 'user_box_id' => ['in', $box_ids]])->delete();
        $this->success();
    }

    public function addboxgoods() {
        $id = input('goods_id', 0, 'intval');
        $box_ids = $this->request->param('ids');

        $box_ids = explode(',', $box_ids);
        $quarters_id = db('user_box')->where(['user_box_id' => ['in', $box_ids]])->group('quarters_id')->value('quarters_id');

        $data['goods_id'] = $id;

        $data['selling_price'] = db('house_goods')->where(['house_id' => $quarters_id, 'goods_id' => $id])->value('selling_price');

        foreach ($box_ids as $box) {
            $data['user_box_id'] = $box;
            db('user_box_goods')->insert($data);
        }

        $this->success();
    }

    public function checkno() {
        $user_box_id = input('user_box_id', 0, 'intval');
        $data['refusal_reason'] = input('refusal_reason');
        $data['refusal_time'] = date('Y-m-d H:i:s');
        $data['status'] = 10;
        db('user_box')->where(['user_box_id' => $user_box_id])->update($data);
        $this->success();
    }

    public function checkids() {
        $ids = input('ids');

        if (empty($ids)) {
            $this->error('请选择需要分配的申请');
        }

        $quarters_id = db('user_box')->where(['user_box_id' => ['in', $ids]])->group('quarters_id')->column('quarters_id');
        if (count($quarters_id) > 1) {
            $this->error('请选择相同小区的申请分配盒子');
        } else {
            $this->success();
        }
    }

    public function editstock() {

        $ids = input('ids');
        $goods_id = input('goods_id', 0, 'intval');
        $arrData['stock_num'] = input('stock_num', 0, 'intval');
        db('user_box_goods')->where(['goods_id' => $goods_id, 'user_box_id' => ['in', $ids]])->update($arrData);
        db('user_box_goods')->where(['goods_id' => $goods_id, 'user_box_id' => ['in', $ids]])->update(['total_num' => $arrData['stock_num']]);
        $this->success();
    }

}
